import { BaseUtil } from "../util/BaseUtil";
import { Constants } from "../data/Constants";
import { BaseValue } from "../data/BaseValue";
import { Bullet } from "./Bullet";
import { Fish } from "./Fish";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ColliderListener extends cc.Component {

    /**
     * 碰撞边界
     */
    private _collisionBorder = {
        'top_collider': 1,
        'bottom_collider': 1,
        'left_collider': 1,
        'right_collider': 1
    };


    /**
     * 碰撞发生时调用
     * @param other  产生碰撞的另一个组件
     * @param self   产生碰撞的自身组件(加载了该碰撞文件的组件)
     */
    onCollisionEnter(other: cc.Collider, self: cc.Collider) {
        let selfName = self.node.name;

        if (!BaseUtil.isEmpty(selfName) && this._collisionBorder[selfName] && this._collisionBorder[selfName] === 1) {
            other.node.stopAllActions();
            let degress = other.node.angle;
            // 顶部和底部
            if (selfName === Constants.CollisionBorder.TOP || selfName === Constants.CollisionBorder.BOTTOM) {
                degress -= 180;
            }
            other.node.angle = -degress;
            let radian = (2 * Math.PI / 360) * (-degress - 270);
            let x = other.node.x + Math.cos(radian) * 2000;
            let y = other.node.y + Math.sin(radian) * 2000;

            let bullet = other.node.getComponent(Bullet);
            if (bullet.bullet.spriteFrame.name.startsWith('bullet')) {
                cc.tween(other.node)
                    .to(BaseValue.BULLET_SPEED, { position: cc.v2(x, y) })
                    .start();
            } else {
                other.node.destroy();
            }

        } else {
            let fishNode = self.node.getChildByName('fish');
            let fish = self.getComponent(Fish)
            if (fish) {
                let bullet = other.node.getComponent(Bullet);
                let attackValue = bullet.collisionFish(other);

                let gold = fish.collisionBullet(self, attackValue);
                if (gold > 0) {
                    BaseValue.GOLD_COINS += gold;
                }

            }
        }
    }


    /**
     * 碰撞发生过程中,每次计算碰撞结果后调用
     * @param other 
     * @param self 
     */
    onCollisionStay(other: cc.Collider, self: cc.Collider) {

    }

    /**
     * 碰撞结束后调用
     * @param other 
     * @param self 
     */
    onCollisionExit(other: cc.Collider, self: cc.Collider) {
        let fishNode = self.node.getChildByName('fish');
        if (fishNode) {
            fishNode.color = cc.Color.WHITE;
        }

    }

}
